<template>
  <!-- 角色管理 -->
  <div>
    <h3 class="notitle">当前页面：{{ $route.meta.title }}</h3>
    <div class="pb10px">
      <!-- ctrl+alt+l 格式化代码   -->
      <el-input v-model="searchForm.roleName"  class="input1" clearable placeholder="请输入角色名"
                size="small" ></el-input>
      <el-button type="primary" icon="el-icon-search" size="small" class="mr10px" @click="handleSearch">搜索</el-button>
    </div>

    <div>
      <el-button type="primary" @click="handleAdd" size="small">新增</el-button>
      <!-- <el-button type="danger" size="small" @click="batchDelete" :disabled="ids.length>0?false:true">批量删除
      </el-button> -->
    </div>

    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="id"
          label="ID"
          width="50">
      </el-table-column>
     
      <el-table-column
          prop="roleName"
          label="角色名"
          width="220">
      </el-table-column>
      <el-table-column
          prop="roleDesc"
          label="角色描述"
          width="220">
      </el-table-column>

      <el-table-column
          prop="rolePermission"
          label="已拥有权限"
          width="550"
          
          show-overflow-tooltip="true"
          :formatter="formatRolePermission">
          <!-- :formatter="formatRolePermission  允许你在渲染一个元素的内容时应用一个函数。这个函数会接收一个参数，通常是当前行的数据对象，然后返回一个新的值，这个值会被用来替换原来的内容。-->
      </el-table-column>
      
      <!--      fixed="right"-->
      <el-table-column label="操作"
                       width="300"
                       align="center">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑角色信息
          </el-button>
          <el-button
              size="mini"
              type="primary"
              @click="setPermisson(scope.row.id)">编辑权限
          </el-button>
          <!-- scope.row.id获取当前行id -->
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--自定义分页组件-->
    <custom-pages
        @current-change="currentChange"
        @size-change="sizeChange"
        :total="pageInfo.total"
        :page-size="pageInfo.pageSize"
        :current-page="pageInfo.pageNum"
        class="custom-pages"
    >
    </custom-pages>
    <!--自定义分页组件-->

    <!--自定义抽屉组件-->
    <custom-drawer
        :form-data="formData"
        :rules-form="ruleForm"
        @close-drawer="closeDrawer"
        @submit-drawer="submitDrawer"
        :is-drawer-dialog="isDrawerDialog"
    >
      <div slot="content">
        <el-form-item label="角色名" prop="roleName" >
          <el-input v-model="formData.roleName" placeholder="请输入角色名"></el-input>
        </el-form-item>
       
        <el-form-item label="角色描述" prop="roleDesc" >
          <el-input v-model="formData.roleDesc" placeholder="请输入角色描述"></el-input>
        </el-form-item>


      </div>
    </custom-drawer>
    <!--自定义抽屉组件-->

    <!-- 配置权限对话框 -->
    <el-dialog title="角色权限配置" :visible.sync="dialogTableVisible" :before-close="handleClose">
      <h3>当前角色ID：{{ id }} </h3>
      <el-table :data="permissionList" ref="roleTable"
      @selection-change="selectionChange">
        <!-- type=selection 多选框 show-overflow-tooltip单行展示 
        selection-change选中修改-->
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column property="perName" label="权限名称" width="200" 
        class="show-overflow-tooltip" ></el-table-column>
        <el-table-column property="perDesc" label="权限描述" width="200" 
        class="show-overflow-tooltip" ></el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="nosumbit">取 消</el-button>
        <el-button type="primary" @click="sumbitEdit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
        title="提示"
        :visible.sync="error"
        width="30%"
        append-to-body
        top="20%"
        ><!-- append-to-body出现不会屏幕变暗,top位置下调 -->
        <span>{{ message }}</span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="error = false">取 消</el-button>
            <el-button type="primary" @click="error = false">确 定</el-button>
        </span>
        </el-dialog>

  </div>
</template>

<script>

//引入混入
import create from "@/mixins/create"
import http from "@/utils/request";


export default {
  data() {
    //页面格式化 ctrl+alt+l
    return {
      api: {
        pageUrl: "/system/getrolepermission",//获取角色数据列表
        saveUrl: "/system/addrole",//增加一个角色
        delUrl: "/system/deleterole",//删除一个角色
        modUrl:"/system/updaterole",//修改角色权限 
        search:"/system/selectrolepermission",
      },
      ruleForm: {
        roleName: [
          {required: true, message: '请输入角色名', trigger: 'blur'},
        ],
        roleDesc: [
          {required: true, message: '请输入角色描述', trigger: 'blur'},
        ],
        
      },
     
      formData: {
        id: null,
        roleName: "", //新增的角色名称
        roleDesc:"",//角色描述
       
      },
      searchForm: {
        roleName: ""
      },
      options: [{
          value: '选项1',
          label: '黄金糕'
        }, {
          value: '选项2',
          label: '双皮奶'
        }, ],
      value: '',
      
      // error:false,//错误提示弹窗
      message:'',//接口返回提示信息
      judge1: null,
      dialogTableVisible:false,//默认关闭弹出对话框
      permissionList: [], //多选框数据
      roleList:[],//当前选中角色已拥有权限
      roleTable:[],//当前选中数据信息,数组
      id:0,//当前行id
    }
  },
  mixins: [create],
  created() {
    this.getpermission()
    
  },
  methods: {
    //显示已拥有权限
    formatRolePermission(row) {
      // 这里的 row.rolePermission 是你从后端接收到的 rolePermission 数据
      let permissionStr = '';
      let permissname = '';
      for (let i = 0; i < row.rolePermission.length; i++) {
        permissionStr += row.rolePermission[i].id + '  ';
        permissname += row.rolePermission[i].perDesc + ', ';
      }
      return permissionStr,permissname;
    },

    //获取权限信息到编辑权限弹出框
    getpermission(){
      
      
      http.get('/system/getpermission').then((res)=>{
        if(res.data.code==200){
          this.permissionList=res.data.data
        }
        
        
      })
    },
    //查询当前角色已拥有权限
    getmission(){
      let formData = {
                  //当前页
                  pageNum: this.pageInfo.pageNum,
                  //分页大小
                  pageSize:this.pageInfo.pageSize,
                  //总条数
                  total: this.pageInfo.total,
      };
      http.get(`${'/system/getrolepermission'}?${new URLSearchParams(formData).toString()}`).then((res)=>{
        if(res.data.code==200){
          this.roleList=res.data.data.records
        }
        
        //配置菜单复选
        let setdata= []
        // console.log(this.roleList)
        // console.log(this.permissionList)
        this.roleList.forEach(item => {
          //选中返回数据中当前行的数据
          if(item.id == this.id){
            item.rolePermission.forEach(item2 => {
          //后端返回的数据和前端表格中的数据进行对比，相同则进行添加选中
          
          this.permissionList.forEach(i=>{
             
              if(item2.id == i.id){
                 
                  setdata.push(i)
              }
            })
          });
          }
          
          
        });
        //已有权限选中操作
        setdata.forEach(item=>{
          this.$refs.roleTable.toggleRowSelection(item)
        })

      })
    },
    //编辑权限弹出框
    setPermisson(id){
      // this.roleTable = []
      // this.$refs.roleTable.clearSelection();//清空数据
      this.dialogTableVisible=true
      this.id=id //将传进来的参数给id
      this.getmission()
      
      
    },
    //
    selectionChange(e){
      
      this.roleTable=e
     
    },
    //提交配置菜单
    sumbitEdit(){
      
      let data={
        id:this.id,
        rolePermission:this.roleTable
      }
      // console.log(data)
      //
      http.post('/system/managerolepermission',data).then((res)=>{
        console.log(res.data.data)
        if (res.data.code == 200) {
            this.$message({
                message: res.data.msg,
                type: 'success'
            });
          this.getList()
          this.getpermission()
        }
        else{
          this.message= res.data.msg,
          this.error=true,
          // this.$message({
          //       message: res.data.msg,
          //       type: 'error'
          // });
          this.getList()
          this.getpermission()
        }
      })
      this.dialogTableVisible=false
    },
    //单个删除
    handleDelete(index, row) {
            // console.log(index, row);
            this.ids = [row.id]
            // this.batchDelete()
            const id =this.ids[0];
            let formData = {
                id: id,
            };
            //
            this.$confirm(`此操作将永久删除ID为[${this.ids[0]}]的数据, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                http.delete(`${this.api.delUrl}?${new URLSearchParams(formData).toString()}`).then(res => {
                    // console.log(res)
                    if (res.data.code == 200) {
                        this.$message({
                            message: res.data.msg,
                            type: 'success'
                        });
                        this.getList()
                    }
                    else{
                        this.message= res.data.msg,
                        this.error=true,
                        this.getList()
                    }
                })
            }).catch(() => {
                // this.message=res.data.msg,
                // this.error=true,
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
                this.$refs.multipleTable.clearSelection();
            });
        },
    //设置配置权限的取消和叉号的点击事件
    nosumbit(){
      this.dialogTableVisible=false
      this.getList()
      this.getpermission()
    },
    handleClose() {
      this.dialogTableVisible=false
      this.getList()
      this.getpermission()
      
    },
     //搜索
     handleSearch() {
            let formData1={
                //当前页
                pageNum: this.pageInfo.pageNum,
                //分页大小
                pageSize:this.pageInfo.pageSize,
                userId:sessionStorage.getItem('userId'),
                roleName:this.searchForm.roleName,
            }
            
            http.get(`${this.api.search}?${new URLSearchParams(formData1).toString()}`).then(res => {
                    // console.log(res)
                    if (res.data.code == 200) {
                        console.log(res)
                        this.message=res.data.msg,
                        this.error=true,
                        //更换表格数据
                        this.tableData = res.data.data.records
                        this.pageInfo.total = res.data.data.total//动态获取分页
                    }
                    else {
                        this.message=res.data.msg,
                        this.error=true,
                        this.getList()
                    }
                })
        },
  },
  
};
</script>

<style scoped>
.input1{
  width: 260px;
}
.notitle{
    color: black;
    font-size:25px;
    margin-top: 1%; 
    margin-left: 0%;
  }/* 面包屑 */
  .custom-pages {
      position: absolute;
      /* position: relative; */
      top: 100%;
      /* 设置其始终位于页面底部 */
  } 
</style>